package myJs.user.mission

import myJs.Implicits._
import myJs.Utils._
import scala.scalajs.js.Dynamic.{global=>g}
import myJs.myPkg.jquery._
import myJs.myPkg._
import myJs.tool.Tool
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._
import scalatags.Text.{TypedTag, all}
import shared.VarTool

import scala.collection.SeqMap
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("Long2wideResult")
object Long2wideResult {
  val formId = "form"
  val tableId = "table"

  @JSExport("init")
  def init = {

    refreshMissionInfo(getMissionId)
    refreshData

  }

  def refreshData = {
    val url = g.jsRoutes.controllers.MissionController.getFileData().url.toString
    Ajax.get(url = s"${url.noCache}&missionId=${getMissionId}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val columnNames = rs("columnNames").asInstanceOf[js.Array[String]]
      val columns = columnNames.map { columnName =>
        val fmt = columnName
        ColumnOptions.field(columnName).title(columnName).sortable(true)
      }
      val exportOptions = ExportOptions.fileName("result.csv")
      val options = TableOptions.data(rs("array")).columns(columns).exportOptions(exportOptions).showExport(true).
        exportDataType("all").exportTypes(js.Array("csv"))
      $(s"#${tableId}").bootstrapTable(options)
    }
  }

  def getMissionId = {
    g.missionId.toString
  }

  def refreshMissionInfo(missionId: String) = {
    val url = g.jsRoutes.controllers.MissionController.getMissionById().url.toString
    Ajax.get(url = s"${url.noCache}&missionId=${missionId}").map { xhr =>
      val dict = JSON.parse(xhr.responseText).toJDS
      dict.foreach { case (k, v) =>
        val trueV = k match {
          case "kind" => Tool.getKindA(v)
          case "state" => Tool.successA
          case _ => span(v)
        }
        $(s"#mission #${k}").html(trueV.render)
      }
    }
  }

}
